package com.xuemeng.web;


import com.github.pagehelper.PageHelper;
import com.xuemeng.entity.Tcustomer;
import com.xuemeng.entity.Trole;
import com.xuemeng.entity.Ttrail;
import com.xuemeng.entity.Tuser;
import com.xuemeng.model.JqgridBean;
import com.xuemeng.model.PageRusult;
import com.xuemeng.service.TcustomerService;
import com.xuemeng.service.TtrailService;
import com.xuemeng.service.TuserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author xuemeng
 * @date 2018/12/12 22:03
 * 客户跟进信息操作类
 */
@Controller
@RequestMapping("/trail")
public class TrailController {

        @Resource
        private TtrailService trailService;
        @Resource
        private TcustomerService tcustomerService;
        @Resource
        private TuserService tuserService;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        /**
         * 进入客户跟进主页面
         *
         * @return
         */
        @RequestMapping("/toTrailManage")
        @RequiresPermissions(value = {"我的客户"})
        public String toGroupManage() {

                return "content/trail";
        }
        /**
         * 进入客户跟进主页面
         *
         * @return
         */
        @RequestMapping("/toMyTrailManage")
        @RequiresPermissions(value = {"跟进记录"})
        public String toMyTrailManage() {

                return "content/myTrailCustomer";
        }

        /**
         * 分页查询角色信息
         */

        @ResponseBody
        @RequestMapping(value = "/list")
        @RequiresPermissions(value = {"我的客户"})
        public Map<String, Object> list(JqgridBean jqgridbean,String customerId,HttpServletRequest request) throws Exception {
                LinkedHashMap<String, Object> resultmap = new LinkedHashMap<String, Object>();
                LinkedHashMap<String, Object> datamap = new LinkedHashMap<String, Object>();
                Tuser user=(Tuser) request.getSession().getAttribute("currentUser");
                Trole role=(Trole)request.getSession().getAttribute("currentRole");
                Example troleExample = new Example(Ttrail.class);
                //排序
                troleExample.setOrderByClause("create_time DESC");
                Example.Criteria criteria = troleExample.and();

                criteria.andEqualTo("customerId",customerId);
                if (role.getName().equalsIgnoreCase("业务员角色")) {
                        troleExample.and().andEqualTo("userId", user.getId());
                }
                if (role.getName().equalsIgnoreCase("部门主管角色")) {
                        Example userExample = new Example(Tuser.class);
                        Example.Criteria cri = userExample.and();
                        cri.andEqualTo("deptId",user.getDeptId());
                        List<Tuser> userList = tuserService.selectByExample(userExample);
                        Collection<String> a = new ArrayList<String>();
                        for (Tuser tuser:userList){
                                a.add(tuser.getId()+"");
                        }
                        //Iterator<String> iterator=a.iterator();
                        troleExample.and().andIn("userId",a);
                }
                if (role.getName().equalsIgnoreCase("总经理角色") || role.getName().equalsIgnoreCase("管理员")) {
                        troleExample.and().andIsNotNull("userId").orNotEqualTo("userId","");
                }
                if (role.getName().equalsIgnoreCase("售后服务员")) {
                        //troleExample.and().andIsNotNull("userId").orNotEqualTo("userId","");
                        troleExample.and().andLike("groupName", "A");
                }
                if (StringUtils.isNotEmpty(jqgridbean.getSearchField())) {
                        if ("userName".equalsIgnoreCase(jqgridbean.getSearchField())) {
                                        criteria.andLike("userName",jqgridbean.getSearchString());
                        }
                        if ("customerName".equalsIgnoreCase(jqgridbean.getSearchField())) {
                                criteria.andLike("customerName", jqgridbean.getSearchString());
                        }
                        if ("content".equalsIgnoreCase(jqgridbean.getSearchField())) {
                                criteria.andLike("content", jqgridbean.getSearchString());
                        }
                        if ("customerTel".equalsIgnoreCase(jqgridbean.getSearchField())) {
                                criteria.andLike("customerTel", jqgridbean.getSearchString());
                        }
                }

                PageHelper.startPage(jqgridbean.getPage(), jqgridbean.getLength());
                List<Ttrail> trailList = trailService.selectByExample(troleExample);
                PageRusult<Ttrail> pageRusult = new PageRusult<Ttrail>(trailList);

                resultmap.put("currpage", String.valueOf(pageRusult.getPageNum()));
                resultmap.put("totalpages", String.valueOf(pageRusult.getPages()));
                resultmap.put("totalrecords", String.valueOf(pageRusult.getTotal()));
                resultmap.put("datamap", trailList);

                return resultmap;
        }


        @ResponseBody
        @RequestMapping(value = "/addUpdateTrail")
        @RequiresPermissions(value = {"我的客户"})
        public Map<String, Object> addUpdateGroup(Ttrail trail, HttpServletRequest request) {
                LinkedHashMap<String, Object> resultmap = new LinkedHashMap<String, Object>();
                Tuser user=(Tuser) request.getSession().getAttribute("currentUser");
                trail.setUserId(user.getId()+"");
                trail.setUserName(user.getTrueName());
                try {
                        if (trail.getId() == null) {//新建
                                trail.setCreateTime(format.format(new Date()));
                                trailService.saveNotNull(trail);
                        } else {//编辑
                                Ttrail oldObject = trailService.selectByKey(trail.getId());
                                if (oldObject == null) {
                                        resultmap.put("state", "fail");
                                        resultmap.put("mesg", "当前跟进信息不存在");
                                        return resultmap;
                                } else {
                                        trail.setCreateTime(format.format(new Date()));
                                        trailService.updateNotNull(trail);
                                }
                        }
                        //新增还是编辑跟进记录  都是要修改客户更新时间
                        Tcustomer tcustomer=tcustomerService.selectByKey(Integer.parseInt(trail.getCustomerId()));
                        if (tcustomer!=null){
                                tcustomer.setUpdateTime(format2.format(new Date()));
                                tcustomerService.updateNotNull(tcustomer);
                        }

                        resultmap.put("state", "success");
                        resultmap.put("mesg", "操作成功");
                        return resultmap;
                } catch (Exception e) {
                        e.printStackTrace();
                        resultmap.put("state", "fail");
                        resultmap.put("mesg", "操作失败，系统异常");
                        return resultmap;
                }
        }


        @ResponseBody
        @RequestMapping(value = "/deleteTrail")
        @RequiresPermissions(value = {"我的客户"})
        public Map<String, Object> deleteuser(Ttrail trail) {
                LinkedHashMap<String, Object> resultmap = new LinkedHashMap<String, Object>();
                try {
                        if (trail.getId() != null && !trail.getId().equals(0)) {
                                Ttrail role = trailService.selectByKey(trail.getId());
                                if (role == null) {
                                        resultmap.put("state", "fail");
                                        resultmap.put("mesg", "删除失败,无法找到该记录");
                                        return resultmap;
                                } else {

                                        trailService.delete(trail.getId());
                                }
                        } else {
                                resultmap.put("state", "fail");
                                resultmap.put("mesg", "删除失败");
                        }


                        resultmap.put("state", "success");
                        resultmap.put("mesg", "删除成功");
                        return resultmap;
                } catch (Exception e) {
                        e.printStackTrace();
                        resultmap.put("state", "fail");
                        resultmap.put("mesg", "删除失败，系统异常");
                        return resultmap;
                }
        }


        @ResponseBody
        @RequestMapping(value = "/selectTrailById")
        @RequiresPermissions(value = {"我的客户"})
        public Map<String, Object> selectRoleById(Ttrail trail) {
                LinkedHashMap<String, Object> resultmap = new LinkedHashMap<String, Object>();
                try {
                        if (trail.getId() != null && !trail.getId().equals(0)) {
                                trail = trailService.selectByKey(trail.getId());
                                if (trail == null) {
                                        resultmap.put("state", "fail");
                                        resultmap.put("mesg", "无法找到该记录");
                                        return resultmap;
                                }
                        } else {
                                resultmap.put("state", "fail");
                                resultmap.put("mesg", "无法找到该记录的id");
                                return resultmap;
                        }

                        resultmap.put("trail", trail);
                        resultmap.put("state", "success");
                        resultmap.put("mesg", "获取成功");
                        return resultmap;
                } catch (Exception e) {
                        e.printStackTrace();
                        resultmap.put("state", "fail");
                        resultmap.put("mesg", "获取失败，系统异常");
                        return resultmap;
                }
        }





}
